<?php


class NconfigApi extends ApiBase{

	private static $cache = array();
	private $mysql = '';

	public $type = array(
						0=>"字符串",
						1=>"布尔",
						2=>"整形",
						10=>"单选",
						11=>"复选"
					);

	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		parent::__construct();
		$this->mysql = n_api("mysql")->db001;
	}
	
	
	/**
	 * 返回结果为pevent-ckey，避免两个插件重复的ckey
	 * 2013年12月20日 去掉了pevent可选的情况。必须指定pevent
	 */
	public function siteGet($scode, $pevent, $ckey){
		$mysql = n_api("mysql")->db001;
		$sql = "SELECT a.id, a.title, a.data FROM nconfig_data_site AS a
				LEFT JOIN nconfig_template_main AS b ON a.template_id = b.id
				WHERE scode = '{$scode}' AND pevent = '{$pevent}' AND ckey = '{$ckey}'";
		$data = $mysql->select($sql);

		$rs = array();
		if(! empty($data)) {
			foreach ($data as $row) {
				$rs[] = array(
					'id' => $row['id'], 'title' => $row['title'],
					'data' => json_decode($row['data'], true),
				);
			}
		}
		return $rs;
	}

	/**
	 * 获取配置项及数据。
	 * linruiyan@2012-11-28 在某些页面会发现大量的执行配置项获取。通过静态变量来充当一定的缓存
	 */
	
	public function get($id){

		$args = func_get_args();

		$rs = array();
		
		//如果静态变量已经获取过该值。那么就直接从静态变量中取
		foreach ($args as $key => $val) {
			if(isset(self::$cache[$val])){
				$rs[$val] = self::$cache[$val];
				unset($args[$key]);
			}
		}
		//静态变量中未存在该变量的。那么就从数据库中取
		if(!empty($args)){

			
			$data = $this->mysql->select("select * from nconfig_main where id in('".implode("','", $args)."')");
			
			if(!empty($data)){				
			foreach ($data as $key => $val) {
				$rs[$val['id']] = $val['value'];
				self::$cache[$val['id']] = $val['value'];
				
				unset($args[array_search($val['id'], $args)]);
			}
			}
		}
		
		//linruiyan@2012-11-28 配置项是开发时预先定义好的。所以找不到说明数据有缺失。应该给予直接响应
		if(!empty($args)){
			throw new PException("找不到配置项".implode(',', $args));
		}
		return $rs;
	}
	
	
	public function set($id,$val){
		
		
		//echo $val.'===';
		$info = $this->mysql->fetchFirst("select * from nconfig_main where id='{$id}'");
		if(empty($info)){
			return n_state(FALSE, "找不到变量");
		}
		$this->mysql->update("nconfig_main",array("value"=>$val),"id='{$id}'");
		return n_state(TRUE, "保存成功");
	}

	public function getSiteByCkey($ckey,$pevent=''){
		$psql = empty($pevent)?'':" and pevent='{$pevent}'";
		
		$mysql = n_api("mysql")->db001;
		return $mysql->select("select * from nconfig_site where ckey='{$ckey}'{$psql}");
	}

	/**
	 * 通过id获取站点的配置信息
	 */
	public function getSiteById($id){
		return n_api("mysql")->db001->get("nconfig_site", intval($id));
	}

	/**
	 * [updatSiteById description]
	 * @param  [type] $id  [description]
	 * @param  [type] $val [description]
	 * @return [type]      [description]
	 */
	public function updatSiteById($id,$val){
		$mysql = n_api("mysql")->db001;
		$mysql->exec("update nconfig_site set value='{$val}' where id='{$id}' limit 1");
		return true;
	}

	public function getSite($scode,$pevent='',$ckey=''){
		//开发阶段缓存机制尚未完善，先注释掉缓存功能
		/*$c_db_k 	= 'NCONFIG_GET_SITE_LIST';
		$ncif		= n_api('nconfig')->get($c_db_k);
		$block_key	= $ncif[$c_db_k];
		$redis		= n_api("redis")->c001;

		$cache = $redis->hmGetAll($block_key);// hmGetElment($block_key,arr);
		
		if(empty($cache[$scode])){*/
			static $cache = array();
			if(!isset($cache[$scode])){
				
				$mysql = n_api("mysql")->db001;
				$sql = "select * from nconfig_site where scode='{$scode}'";
				if(!empty($pevent)){
					$sql.= " and pevent='{$pevent}'";
				}
	
				if(!empty($ckey)){
					$sql.= " and ckey='{$ckey}'";
				}
	
				$data = $mysql->select($sql);
				$rs = array();
				if(!empty($data)){
					foreach($data as $key=>$val){
						$rs[$val['pevent'].'-'.$val['ckey']] = $val;
					}
					$cache[$scode] = $rs;
					//$redis->hmSave($block_key,$cache);
				}
			}
		//}

		return $cache[$scode];
	}
	
	public function setSite($scode,$pevent,$ckey,$val){
		$mysql = n_api("mysql")->db001;
		$cinfo = $this->getSite($scode,$pevent,$ckey);
		if(empty($cinfo)){
			throw new PException("找不到配置项".$ckey);
		}
		$mysql->exec("update nconfig_site set value='{$val}' where scode='{$scode}' and pevent='{$pevent}' and ckey='{$ckey}' limit 1");
		return true;
	}

	/**
	 * [addSite description]
	 * @param [type] $data [description]
	 */
	public function addSite($data){
		if ($data['scode']=='' || $data['pevent']=='' || $data['ckey']=='') {
			throw new PException("参数错误！");
		}

		$mysql = n_api("mysql")->db001;
		$cinfo = $this->getSite($data['scode'],$data['pevent'],$data['ckey']);

		if(!empty($cinfo[$data['pevent'].'-'.$data['ckey']])){
			throw new PException("配置项".$data['ckey']."已经存在！");
		}
		$rs = $mysql->insert("nconfig_site",$data);
		return $rs;
	}
	
	/**
	 * 根据id获取配置信息
	 * @param $id string 
	 * @param $type string $type!=''时 模糊查询 
	 */
	public function getInfoById($id,$type=''){
		if($type != ''){
			$data = $this->mysql->select("select * from nconfig_main where id like('{$id}{$type}')");
		}else{
			$data = $this->mysql->select("select * from nconfig_main where id = '{$id}')");
		}
		
		return $data;
	}


	public function pluginsUpdate($data){
		$pevent = N_EVENT;
		try{
			$mysql = n_api("mysql")->db001;
			foreach($data as $ckey=>$val){
				$info = $this->pluginsGet($pevent, $ckey);
				if(empty($info)){
					throw new PException("找不到预定义值:{$ckey}");
				}
				$mysql->update("nconfig_plugins",array("value"=>$val),"id={$info['id']}");
			}
			$rs = n_state(TRUE, "更新成功");
		}catch(PException $p){
			$rs = n_state(FALSE, $p->getMessage());
		}
		return $rs;
	}

	public function getTemplateInfo($pevent, $ckey) {
		$sql = "SELECT m.name, i.ukey, i.default
				FROM nconfig_template_main AS m JOIN nconfig_template_items AS i
				ON m.id = i.main_id
				WHERE m.pevent = '{$pevent}' AND m.ckey = '{$ckey}'";
		$data = n_api('mysql')->db001->select($sql);

		$rs = array();
		foreach ($data as $row) {
			$rs['name'] = $row['name'];
			$rs['items'][$row['ukey']] = $row['default'];
		}

		return $rs;
	}

	public function siteSet($scode, $pevent, $ckey, $title, $data) {
		$mysql = n_api('mysql')->db001;
		$sql = "SELECT id FROM nconfig_template_main
				WHERE pevent = '{$pevent}' AND ckey = '{$ckey}'";
		$rs = $mysql->fetchFirst($sql);
		$items = $mysql->select($sql);
		$data = array(
			'scode' => $scode, 'template_id' => $rs['id'],
			'title' => $title, 'data' => json_encode($data),
		);
		$mysql->insert('nconfig_data_site', $data);
	}

	public function clearConfig($scode) {
		$mysql = n_api("mysql")->db001;
		$sql = "SELECT id FROM nconfig_data_site WHERE scode = '{$scode}'";
		$data = $mysql->select($sql);

		foreach ($data as $row) {
			$mysql->rm('nconfig_data_site', $row['id']);
		}

		return TRUE;
	}
	
	/**
	public function pluginsGet($pevent,$ckey){
		return n_api("mysql")->db001->fetchFirst("select * from nconfig_plugins where pevent='{$pevent}' and ckey='{$ckey}'");
	}
	public function pluginsGetAll($pevent){
		$data = n_api("mysql")->db001->select("select * from nconfig_plugins where pevent='{$pevent}'");
		if(!empty($data)){
		foreach($data as $key=>$val){
			$rs[$val['ckey']] = $val['value'];
		}
		}
		return $rs;
	}


	public function pluginsSet($pevent,$ckey,$val){
		
	}

	
	public function init(){
		$rs = $this->get('sys_isopen');
		if('N'==$rs['sys_isopen'] && !in_array(N_EVENT,array('open','error'))){
			n_go(n_url('error','http500',array('msg'=>"系统升级维护，请稍后访问！")));
		}
		
	}
	 * 
	 */

	/**
	 * copyConfig 使用源站点的配置覆盖目标站点的配置
	 *
	 * @param $src 源站点代码
	 * @param $dst 目标站点代码
	 */
	public function copyConfig($src, $dst) {
		if (empty($src) || empty($dst) || $src == $dst ||
			! n_api('nsite')->checkNConfReplace($dst)) {
			return FALSE;
		}

		$dst_config = $this->getAllConfig($dst);
		$table = 'nconfig_data_site';
		$mysql = n_api("mysql")->db001;
		foreach ($dst_config as $row) {
			$mysql->rm($table, $row['id']);
		}

		$src_config = $this->getAllConfig($src);
		foreach ($src_config as &$row) {
			unset($row['id']);
			$row['scode'] = $dst;
		}
		
		if (empty($src_config)) {
			return TRUE;
		}

		$fields = array('scode', 'template_id', 'title', 'data');
		return (bool) $mysql->saveMany($table, $fields, $src_config);
	}

	/**
	 * getAllConfig 获取某站点的所有配置数据
	 *
	 * @param $scode 站点代码
	 */
	private function getAllConfig($scode) {
		$mysql = n_api("mysql")->db001;
		$sql = "SELECT * FROM nconfig_data_site WHERE scode = '{$scode}'";
		return $mysql->select($sql);
	}
}
